from 链表 import DoubleNode, LinkedList

"""
j:位序 i:索引

===== 2022.03.11 =====
1.双链表仅实现带头结点的
2.按位序查找及删除（更贴合链表抽象数据类型定义），位序从1开始
3.增加表示链表长度的数据（用头节点）
"""


class DoubleLinkedList(LinkedList):
    """双向链表"""

    def __init__(self):
        super().__init__()
        self.head = DoubleNode(data=0)
        self.content.append(self.head)

    def insert_by_index(self, node_to_insert: DoubleNode, index):
        """index： 链表中的位序,在index后插入一个元素"""
        if index > self.length:
            print("位序不合法")
            return False
        j = 1
        cur = self.head
        while j < index and cur:
            cur = cur.next_node
            j += 1
        node_to_insert.next_node = cur.next_node
        node_to_insert.pre = cur
        # 如果没下个节点（最后一个节点），就不需要修改它的前置节点了
        if cur.next_node:
            cur.next_node.pre = node_to_insert
        cur.next_node = node_to_insert
        # 长度加一
        self.head.data += 1
        return True

    def get_element_by_index(self, index):
        """根据位序查找元素"""
        if index > self.length:
            print("位序不合法")
            return False
        cur = self.head
        j = 0
        while j < index:
            cur = cur.next_node
            j += 1
        return cur

    def get_element_index(self, element):
        """根据元素查找位序"""
        j = 0
        cur = self.head
        while cur:
            if cur == element:
                return j
            cur = cur.next_node
            j += 1
        if j > self.length or (not cur):
            return 0

    def get_content(self):
        print(self.content)

    def add(self, node):
        self.insert(node, 1)

    def delete_by_index(self, index):
        if index > self.length:
            print("位序不合法")
            return False
        j = 0
        cur = self.head
        while j < index:
            j += 1
            cur = cur.next_node



    @property
    def is_empty(self):
        return False if self.head.data else True

    @property
    def length(self):
        return self.head.data

    def get_direction(self):
        cur = self.head
        while cur is not None:
            print("上一个节点:", cur.pre, "节点名:", cur, " ==> ", "下一节点:", cur.next_node)
            if not cur.next_node:
                break
            cur = cur.next_node


if __name__ == '__main__':
    pass
